package com.gcb.socket;

import com.alibaba.fastjson2.JSON;
import com.gcb.common.socket.SemaphoreUtils;
import com.gcb.common.socket.WebSocketInfoVO;
import com.gcb.common.socket.WebSocketTypeEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.concurrent.Semaphore;

/**
 * websocket 消息处理
 * @author ruoyi
 */
// TODO 暂时关闭socket服务，避免未知风险
//@Component
//@ServerEndpoint("/websocket/{sid}")
public class WebSocketServer {
    /**
     * WebSocketServer 日志控制器
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(WebSocketServer.class);

    /**
     * 默认最多允许同时在线人数100
     */
    public static int socketMaxOnlineCount = 100;

    private static Semaphore socketSemaphore = new Semaphore(socketMaxOnlineCount);

    /**
     * 连接建立成功调用的方法
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) throws Exception {
        boolean semaphoreFlag = false;
        // 尝试获取信号量
        semaphoreFlag = SemaphoreUtils.tryAcquire(socketSemaphore);
        if (!semaphoreFlag) {
            // 未获取到信号量
            LOGGER.error("\n 当前在线人数超过限制数- {}", socketMaxOnlineCount);
            WebSocketInfoVO webSocketInfoVO = new WebSocketInfoVO();
            webSocketInfoVO.setType(WebSocketTypeEnum.OTHER.getCode());
            webSocketInfoVO.setData("当前在线人数超过限制数：" + socketMaxOnlineCount);
            WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(webSocketInfoVO));
            session.close();
        } else {
            // TODO 添加用户
            // WebSocketUsers.put(session.getId(), session);
            WebSocketUsers.put(sid, session);
            LOGGER.info("\n 建立连接 - {}", session + "||||" + sid);
            LOGGER.info("\n 当前人数 - {}", WebSocketUsers.getUsers().size());

            WebSocketInfoVO webSocketInfoVO = new WebSocketInfoVO();
            webSocketInfoVO.setType(WebSocketTypeEnum.OTHER.getCode());
            webSocketInfoVO.setData("连接成功");
            WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(webSocketInfoVO));
        }
    }

    /**
     * 连接关闭时处理
     */
    @OnClose
    public void onClose(Session session) {
        LOGGER.info("\n 关闭连接 - {}", session);
        // 移除用户
        WebSocketUsers.remove(session.getId());
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 抛出异常时处理
     */
    @OnError
    public void onError(Session session, Throwable exception) throws Exception {
        if (session.isOpen()) {
            // 关闭连接
            session.close();
        }
        String sessionId = session.getId();
        LOGGER.info("\n 连接异常 - {}", sessionId);
        LOGGER.info("\n 异常信息 - {}", exception);
        // 移出用户
        WebSocketUsers.remove(sessionId);
        // 获取到信号量则需释放
        SemaphoreUtils.release(socketSemaphore);
    }

    /**
     * 服务器接收到客户端消息时调用的方法
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        LOGGER.info("\n sessionID：{}，收到消息 - {}", session.getId(), message);
        try {
            String messageBody = message.replaceAll("[\\pZ]", "");
            WebSocketInfoVO infoVO = JSON.parseObject(messageBody, WebSocketInfoVO.class);
            if (3 == infoVO.getType()) {
                //XR推送的状态，直接推送全部
                WebSocketUsers.sendMessageToAllByText(messageBody);
            }
        } catch (Exception ex) {
            LOGGER.error("\n sessionID：{}，推送消息异常 - {}", session.getId(), message);
        }
        // String msg = message.replace("你", "我").replace("吗", "");
        // WebSocketInfoVO webSocketInfoVO = new WebSocketInfoVO();
        // if ("heartCheck".equals(message)) {
        //     webSocketInfoVO.setType(WebSocketTypeEnum.HEART_CHECK.getCode());
        // } else {
        //     webSocketInfoVO.setType(WebSocketTypeEnum.OTHER.getCode());
        // }
        // webSocketInfoVO.setData(msg);
        // WebSocketUsers.sendMessageToUserByText(session, JSON.toJSONString(webSocketInfoVO));
    }
}
